<?php


namespace App\Service\Admin;


use App\Dao\TaskDao;
use App\Dao\TaskPushDao;
use App\Model\Task;
use App\Model\TaskPush;
use App\Utils\Log;
use App\Utils\Notice\CooperativeReceivedTaskPush;
use App\Utils\Notice\Sender;
use Hyperf\Contract\LengthAwarePaginatorInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class TaskPushService extends BaseService
{

    /**
     * @Inject()
     * @var TaskDao
     */
    protected $taskDao;

    /**
     * @Inject()
     * @var TaskPushDao
     */
    protected $taskPushDao;

    public function taskIndex(array $where)
    {
        $where = $this->formatWhereRegionToCooperative($where);
        $pageInfo = $this->extractPaginateInfo($where);
        $index = $this->taskDao
            ->where($where)
            ->with([
                'user', 'cooperative'
            ])
            ->paginate(
                $pageInfo['perPage'],['*'],'page',$pageInfo['page']
            );
        return $this->formatTaskIndex($index);
    }

    /**
     * @return array
     */
    public function formatTaskIndex(\Hyperf\Contract\LengthAwarePaginatorInterface $index)
    {
        $data = [];
        /** @var \App\Model\Task $task */
        foreach ($index->items() as $task) {
            $data[] = [
                'task_id' => $task->id,
                'user_name' => $task->user->nickname,
                'user_phone' => $task->user->phone,
                'cooperative_name' => $task->cooperative->nickname,
                'task_price' => $task->price,
                'task_title' => $task->title,
            ];
        }
        return [
            'data' => $data,
            'current_page' => $index->currentPage(),
            'total' => $index->total(),
            'per_page' => $index->perPage()
        ];
    }

    public function index(array $where)
    {
        $where = $this->formatWhereRegionToCooperative($where);
        $where = $this->formatWhereRegionToReceivedCooperative($where);
        $pageInfo = $this->extractPaginateInfo($where);
        $index = $this
            ->taskPushDao
            ->where($where)
            ->with(['user', 'task', 'cooperative', 'receivedCooperative','adminUser'])
            ->paginate(
                $pageInfo['perPage'],['*'],'page',$pageInfo['page']
            );

        return $this->formatIndex($index);
    }

    public function formatIndex(LengthAwarePaginatorInterface $index)
    {
        $data = [];
        /** @var \App\Model\TaskPush $taskPush */
        foreach ($index->items() as $taskPush) {
            $data[] = [
                'user_name' => $taskPush->user->nickname,
                'user_phone' => $taskPush->user->phone,
                'cooperative_name' => $taskPush->cooperative->nickname,
                'receive_cooperative_name' => $taskPush->receivedCooperative->nickname,
                'task_price' => $taskPush->task->price,
                'task_title' => $taskPush->task->title,
                'admin_user_name' => $taskPush->adminUser->username,
                'created_at' => $taskPush->created_at->toDateTimeString()
            ];
        }
        return [
            'data' => $data,
            'current_page' => $index->currentPage(),
            'total' => $index->total(),
            'per_page' => $index->perPage()
        ];
    }

    public function formatWhereRegionToReceivedCooperative($where)
    {
        if (isset($where['received_province'])) {
            if ($where['received_province']) {
                $whereRegion['province'] = $where['received_province'];
            }
            unset($where['received_province']);
        }
        if (isset($where['received_city'])) {
            if ($where['received_city']) {
                $whereRegion['city'] = $where['received_city'];
            }
            unset($where['received_city']);
        }

        if(!empty($whereRegion)){
            $cooperativeIds = $this->cooperativeDao->getCooperativeIdsByRegion($whereRegion);
            $where['received_cooperative_ids'] = $cooperativeIds;
        }
        return $where;
    }

    public function push(array $data)
    {
        /** @var Task $task */
        $task = $this->taskDao->first(['id' => $data['task_id']]);
        Db::beginTransaction();
        try {
            foreach ($data['received_cooperative_ids'] as $receiveCooperativeId) {
                $taskPush = new TaskPush();
                $taskPush->task_id = $task->id;
                $taskPush->user_id = $task->user->id;
                $taskPush->phone = $task->user->phone;
                $taskPush->employer_id = $task->user->id;
                $taskPush->cooperative_id = $task->cooperative_id;
                $taskPush->received_cooperative_id = $receiveCooperativeId;
                $taskPush->admin_user_id = $this->user()->id;
                $taskPush->save();
                Sender::send($receiveCooperativeId, new CooperativeReceivedTaskPush(), true);
            }
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollBack();
            Log::get()->error($exception->getMessage(), $data);
            throw $exception;
        }
        return true;
    }
}